package com.renchunlin.taobaounion.presenter.impl;

import com.renchunlin.taobaounion.model.Api;
import com.renchunlin.taobaounion.model.domain.HomePagerContent;
import com.renchunlin.taobaounion.presenter.ICategoryPagerPresenter;
import com.renchunlin.taobaounion.utils.RetrofitManage;
import com.renchunlin.taobaounion.utils.UrlUtils;
import com.renchunlin.taobaounion.view.ICategoryPageCallback;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CategoryPagePresenterImpl implements ICategoryPagerPresenter {

    Map<Integer, Integer> pageInfo = new HashMap<>();
    public static final int DEFAULT_PAGE = 1;
    private Integer currentPage;

    @Override
    public void getContentByCategoryId(int categoryId) {
        for (ICategoryPageCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoading();
            }
        }
        Integer targetPage = pageInfo.get(categoryId);
        if (targetPage == null) {
            targetPage = DEFAULT_PAGE;
            pageInfo.put(categoryId, DEFAULT_PAGE);
        }

        Call<HomePagerContent> task = createTask(categoryId, targetPage);

        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent body = response.body();
                    //把数据给到ui更新
                    handleHomePageContentResult(body, categoryId);
                } else {
                    handleNetworkError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                handleNetworkError(categoryId);
            }
        });
    }

    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        String homePagerUrl = UrlUtils.createHomePagerUrl(categoryId, targetPage);
        //根据分类id去加载内容
        Retrofit retrofit = RetrofitManage.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        return api.getHomePageContent(homePagerUrl);
    }

    private void handleNetworkError(int categoryId) {
        for (ICategoryPageCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onError();
            }
        }
    }

    private void handleHomePageContentResult(HomePagerContent body, int categoryId) {
        //通知ui层更新数据
        List<HomePagerContent.DataBean> data = body.getData();
        for (ICategoryPageCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (callback == null || callbacks.size() == 0) {
                    callback.onEmpty();
                } else {
                    List<HomePagerContent.DataBean> looperData = data.subList(data.size() - 5, data.size());
                    callback.onLooperListLoadedList(looperData);
                    callback.onContentLoaded(data);
                }
            }
        }
    }

    @Override
    public void loadMore(int categoryId) {
        //加载更多的数据
        //1.拿到当前页
        currentPage = pageInfo.get(categoryId);
        if (currentPage == null) {
            currentPage = 1;
        }
        //2.页码++
        currentPage++;
        pageInfo.put(categoryId, currentPage);
        //3.加载数据
        Call<HomePagerContent> task = createTask(categoryId, currentPage);
        //4.处理数据结果
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                //就结果
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent body = response.body();
                    handleLoaderResult(body, categoryId);
                } else {
                    //请求失败
                    handleLoaderMoreError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                //请求失败
                handleLoaderMoreError(categoryId);
            }
        });
    }

    private void handleLoaderResult(HomePagerContent body, int categoryId) {
        for (ICategoryPageCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (body == null || body.getData().size() == 0) {
                    callback.onLoaderMoreEmpty();
                } else {
                    callback.onLoaderMoreLoaded(body.getData());
                }
            }
        }
    }

    private void handleLoaderMoreError(int categoryId) {
        currentPage--;
        pageInfo.put(categoryId, currentPage);
        for (ICategoryPageCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoaderMoreError();
            }
        }
    }

    @Override
    public void reload(int categoryId) {

    }

    private ArrayList<ICategoryPageCallback> callbacks = new ArrayList<>();

    @Override
    public void registerViewCallback(ICategoryPageCallback callback) {
        if (!callbacks.contains(callback)) {
            callbacks.add(callback);
        }
    }

    @Override
    public void unregisterViewCallback(ICategoryPageCallback callback) {
        callbacks.remove(callback);
    }
}
